const router = require('koa-router')();
const save = require('../utils/report');

router.get('/', async (ctx, next) => {
    await ctx.render('index', {
        title: 'Hello Koa 2!'
    })
})

function decode(url) {
    let reg = /(%(\w|[abcdef])(\w|[abcdef]))+/g   
    let code = url.match(reg)
    let replace_reg = /%/g
    let decode_reg = /(%(\w|[abcdef])(\w|[abcdef]))+/
    for(let i = 0; i < code.length; i ++) {
        code[i] = code[i].replace(replace_reg, "")    //去掉百分号
        code[i] = new Buffer(code[i], "hex").toString()  //转换为utf-8字符
        url = url.replace(decode_reg, code[i])  //替换百分号编码
    }
    return url
}
router.get('/report', async (ctx, next) => {
    let url = ctx.request.url;
    let params = null;
    if(url.indexOf('?') > -1) {
        params = decode(url.slice((url.indexOf('?') + 1), url.length));
    }
    if(params){
        params = JSON.parse(params);
        console.log(params);
        await save(params)
        .then(res => {
            ctx.body = {
                code: 0,
                message: 'success'
            }
        })
        .catch(e => {
            ctx.body = {
                code: 1,
                message: 'failed'
            }
        })
    }
})
module.exports = router
